import json
import os.path
import re
from fileinput import filename
def main():
    ctrl = True
    while ctrl:
        menu()
        option = input("请选择：")
        option_str = re.sub(r"\D","",option)
        if option_str in ['0','1','2','3','4','5','6','7']:
            option_int = int(option_str)
            if option_int==0:
                print("退出系统")
                ctrl = False
            elif option_int==1:
                newAccount()# 新开户
            elif option_int==2:
                modifyInfo()# 信息修改
            elif option_int==3:
                queryInfo()# 信息查询
            elif option_int==4:
                deposit()# 存款
            elif option_int==5:
                withDrow()# 取款
            elif option_int==6:
                changePassword()# 修改密码
            elif option_int==7:
                currencyExchange()# 货币兑换


def menu():
    print('''李星烨 20231205410
          --------III银行管理系统III--------
          =============功能选择============
          1.储户新开户
          2.储户信息修改
          3.储户信息查询
          4.储户存款操作
          5.储户取款操作
          6.修改储户密码
          7.储户货币兑换                   
          0.退出系统                      
          ===============================
          ''')



    # 银行账号、密码、姓名、身份证号、家庭住址、
    # 账户余额（人民币）等信息
def newAccount():# 新开户
    accountList = []
    addOrNot = True # 是否继续添加
    while addOrNot:
        id = input("请输入账号：")
        if not id:# id为空
            break
        password = input("请输入密码：")
        if not password:# id为空
            break
        name = input("请输入姓名：")
        if not name:# id为空
            break
        personId = input("请输入身份证号：")
        if not personId:break
        address = input("请输入家庭住址：")
        if not address:break
        try:
            money = float(input("请输入账户余额(RMB)："))
        except:
            print("不是数字，请重新输入")
            continue
        # 将信息存入到字典
        account = {"id":id,"password":password,"name":name,"personId":personId,"address":address,"money":money}
        accountList.append(account)
        isInput = input("是否继续添加？y（是）/n（否）")
        if isInput == 'n': addOrNot = False
    save(accountList)
    print("信息录入完毕")


def show():
    accountNew = []
    if os.path.exists("accounts.txt"):
        with open("accounts.txt","r") as f:
            accountOld = f.readlines()
        for list in accountOld:
            accountNew.append(eval(list))
        if accountNew:
            showAccount(accountNew)
        else:
            print("暂未保存信息")

def showAccount(accountList):
    if len(accountList)==0:
        print("暂无信息")
        return
    # 定义标题显示格式
    format_title = "{:^6}{:^12}{:^12}{:^12}{:^12}{:^12}"
    print(format_title.format("ID","密码","姓名","身份证号","家庭地址","账户余额(RMB)"))
    format_data = "{:^6}{:^12}{:^12}{:^12}{:^12}{:^12}"
    for info in accountList:
        print(format_data.format(info.get("id"),info.get("password"),info.get("name"),
                                info.get("personId"),info.get("address"),str(info.get("money"))))



def modifyInfo():  # 信息修改
    show()
    if os.path.exists("accounts.txt"):
        with open("accounts.txt","r") as f:
            accountOld = f.readlines()
    else:
        return
    studentId = input("请输入要修改的账号id:")
    with open("accounts.txt","w") as f:
        for account in accountOld:
            d = dict(eval(account))
            if d["id"]==studentId:
                print("找到了这名用户")
                while True:
                    try:
                        d["id"] = studentId
                        d["name"] = input("请输入姓名：")
                        d["password"] = input("请输入密码：")
                        d["personId"] = input("请输入身份证号：")
                        d["address"] = input("请输入家庭地址：")
                        d["money"] = float(input("请输入账户余额："))
                    except:
                        print("输入有误，请重新输入！")
                        continue
                    else:
                        break
                account = str(d)
                f.write(account+"\n")
                print("修改成功！")
            else:
                f.write(account+"\n")
    isOrNot = input("是否要继续修改？是/否（y/n）")
    if(isOrNot=='y'):
        modifyInfo()


def queryInfo():# 信息查询
    isOrNot = True
    account_query = []
    while isOrNot:
        id = ""
        name = ""
        if os.path.exists("accounts.txt"):
            mode = input("按id查请按1，按姓名查请按2:")
            if mode=='1':
                id = input("请输入用户id：")
            elif mode=='2':
                name = input("请输入用户姓名：")
            else:
                print("输入错误请重新输入")
                queryInfo()
            with open("accounts.txt","r") as f:
                accounts = f.readlines()
                for account in accounts:
                    d = dict(eval(account))
                    if id != "":
                        if d["id"]==id:
                            account_query.append(d)
                    elif name != "":
                        if d["name"]==name:
                            account_query.append(d)
                showAccount(account_query)
                account_query.clear()
                isinput = input("是否继续查询？(y/n)")
                if isinput == 'n': isOrNot = False
        else:
            print("暂未保存数据")
            return

def deposit():# 存款
    isOrNot = True
    while isOrNot:
        if os.path.exists("accounts.txt"):
            with open("accounts.txt","r") as f:
                accounts = f.readlines()
        else:
            return
        if os.path.exists("accounts.txt"):
             id = input("请输入用户id：")

             with open("accounts.txt","w") as f:
                 for account in accounts:
                    d = dict(eval(account))
                    if d["id"] == id:
                        password = input("请输入密码：")
                        if password == d["password"]:
                                print(f"您现在的存款是：{d['money']}")
                                money = float(input("请输入存款数额:"))
                                d["money"] += money
                                account = str(d)
                                f.write(account+"\n")
                        else:
                            print("密码错误请重新输入")
                            continue
                    else:
                        f.write(account+"\n")
        a = str(input("是否继续存款？是/否 y/n"))
        if a == 'n': isOrNot = False

def withDrow():# 取款
    isOrNot = True
    while isOrNot:
        if os.path.exists("accounts.txt"):
            with open("accounts.txt", "r") as f:
                accounts = f.readlines()
        else:
            return
        if os.path.exists("accounts.txt"):
            id = input("请输入用户id：")

            with open("accounts.txt", "w") as f:
                for account in accounts:
                    d = dict(eval(account))
                    if d["id"] == id:
                        password = input("请输入密码：")
                        if password == d["password"]:
                            print(f"您现在的存款是：{d['money']}")
                            money = float(input("请输入取款数额:"))
                            if money > d["money"]:
                                print("余额不足，请重新取款")
                                continue
                            d["money"] -= money
                            account = str(d)
                            f.write(account + "\n")
                        else:
                            print("密码错误请重新输入")
                            continue
                    else:
                        f.write(account + "\n")
        a = str(input("是否继续存款？是/否 y/n"))
        if a == 'n': isOrNot = False
def changePassword():# 修改密码
    if os.path.exists("accounts.txt"):
        with open("accounts.txt", "r") as f:
            accounts = f.readlines()
    else:
        return
    if os.path.exists("accounts.txt"):
        id = input("请输入用户id：")
        with open("accounts.txt", "w") as f:
            for account in accounts:
                d = dict(eval(account))
                if d["id"] == id:
                    password = input("请输入原密码：")
                    if password == d["password"]:
                        newPass = input("请输入新密码：")
                        newPass2 = input("请再次输入新密码：")
                        if newPass == newPass2:
                            d["password"] = newPass
                            account = str(d)
                            f.write(account + "\n")
                            print("密码修改成功")
                        else:
                            print("密码错误请重新修改")
                    else:
                        print("密码错误请重新输入")
                        continue
                else:
                    f.write(account + "\n")


def currencyExchange():# 货币兑换
    isOrNot = True
    while isOrNot:
        changeName = input("请输入要兑换的货币类型：（美元，欧元，日元）(1/2/3)")
        changeMon = float(input("请输入要兑换的人民币数量："))
        if changeName == "1":
            changeMon/=7.232
        elif changeName == "2":
            changeMon/=7.676
        elif changeName == "3":
            changeMon/=0.046
        else:
            print("当前不支持此货币兑换，请重新选择")
            continue
        print(f"您兑换的{changeName}数是{changeMon}")
        ch = input("是否继续兑换？是/否（y/n）")
        if ch == 'n': isOrNot = False


def save(account):
    try:
        account_txt = open("accounts.txt",'a')
    except Exception as e:
        account_txt = open("accounts.txt",'w')
    for info in account:
        # 将字典转换为字符串
        account_txt.write(str(info)+"\n")
    account_txt.close()

if __name__ == "__main__":
        main()

